package cn.huaqingcheng.tool.crypto.encrypt;

import cn.huaqingcheng.tool.crypto.codec.Base64Tool;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

/**
 * HMAC
 */
@SuppressWarnings("unused")
public interface HmacSHA1 {

    String HMAC = "HmacSHA1";

    /**
     * HmacMD5 算法所需key
     */
    static byte[] initMacKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(HMAC);
            SecretKey secretKey = keyGenerator.generateKey();
            return secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * HMAC 加密
     *
     * @see #encrypt(byte[], byte[])
     */
    static byte[] encrypt(String input, byte[] key) {
        try {
            return encrypt(input.getBytes(StandardCharsets.UTF_8), key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * HMAC 加密
     *
     * @param input 待加密字节
     * @param key   密钥 {@link #initMacKey()}
     * @return 加密后编码为16禁止字符串
     */
    static byte[] encrypt(byte[] input, byte[] key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, HMAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);

        return mac.doFinal(input);
    }

    /**
     * 加密后的字节数组 转 base64 编码
     *
     * @param input 数据
     * @param key   密钥
     */
    static String encryptToBase64(String input, String key) {
        return Base64Tool.encodeToStr(encrypt(input, key));
    }

    static byte[] encrypt(String input, String key) {
        try {
            return encrypt(
                input.getBytes(StandardCharsets.UTF_8),
                key.getBytes(StandardCharsets.UTF_8)
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
